#include "todoeditor.h"
#include "ui_todoeditor.h"

ToDoEditor::ToDoEditor(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::ToDoEditor)
{
    ui->setupUi(this);
    isEnabled = true;
    pbs = new PublicsWidget(this);
    ui->verticalLayout->addWidget(pbs);
}

ToDoEditor::~ToDoEditor()
{
    delete ui;
}

void ToDoEditor::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type())
    {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void ToDoEditor::saveData()
{
    if (state == "New")
    {
        QString isComplete = "0";
        QString newRef = tr("TODO-%1").arg( myPublics.randomNumber());
        if (ui->chkIsComplete->isChecked())
        {
            isComplete = "1";
        }
        QString query = tr("INSERT INTO todo (RefNumber, Name, Type, Date, Time, SupervisedBy, Completed, ToDoRefNumber) "
                           " VALUES ('%1', '%2', '%3', '%4', '%5', '%6', '%7', '%8')").arg(
                                   RefNo, ui->txtTodoName->text(), ui->txtToDoType->currentText(), ui->dtpToDoDate->text(),
                                   ui->dtpToDoTime->text(), ui->txtSupervisor->text(), isComplete, newRef
                                   );
        QSqlQuery *qu = new QSqlQuery(query, db);
        qu = new QSqlQuery(tr("INSERT INTO publics (RefNumber) VALUES ('%1')").arg(newRef), db);
    }
    else if (state == "Edit")
    {
        QString isComplete = "0";
        if (ui->chkIsComplete->isChecked())
        {
            isComplete = "1";
        }
        QString query = tr( "UPDATE todo SET Name = '%1', Type = '%2', Date = '%3', Time = '%4', SupervisedBy = '%5', Completed = '%6' WHERE ToDoID = '%7'"
                            ).arg(ui->txtTodoName->text(), ui->txtToDoType->currentText(), ui->dtpToDoDate->text(), ui->dtpToDoTime->text(), ui->txtSupervisor->text(), isComplete, ToDoID);
        QSqlQuery *qu = new QSqlQuery(query, db);
        qu->clear();
        pbs->SaveData();
    }
}

void ToDoEditor::showData()
{
    ui->formLayout->setEnabled(isEnabled);
    pbs->RefNumber  = RefNo;
    pbs->LoadData();
    pbs->setEnabled(false);
    if (state == "New")
    {
        pbs->setEnabled(false);
    }
    else if (state == "Edit")
    {
        pbs->setEnabled(true);
        QString query = tr("SELECT * FROM todo WHERE ToDoID = '%1'").arg(ToDoID);
        QSqlQuery *qu = new QSqlQuery(query, db);
        while (qu->next())
        {
            ui->txtTodoName->setText(qu->value(3).toString());
            pbs->RefNumber = qu->value(2).toString();
            pbs->db = db;
            pbs->LoadData();
        }
    }
}

void ToDoEditor::on_buttonBox_accepted()
{
    saveData();
    pbs->SaveData();
}
